package com.tide.crm.utils;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;

import java.io.File;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
 * 腾讯云上传图片
 * @author lishouxu-ds
 *
 */
@Component
public class CosClientUtil {
	private Logger logger = LoggerFactory.getLogger(getClass());
    private String ACCESSID = "AKIDXxCGNNtzio252dMRepLgrslX9tfbjofL";
    private String SECRETKEY ="d7CLPK9qRq4jFblkdN1Vpxyn6EAtRnz0";
    private String BUCKETNAME = "yhjls-1256590735";
    private String APPID = "10194218";
    private String REGIONID = "ap-beijing";
    //private String KEY01="MyFile1/1.jpg";
    /**
     * 初始化CosClient相关配置， appid、accessKey、secretKey、region
     * @return
     */
   /* 
    public   COSClient getCosClient() {
        // 1 初始化用户身份信息(secretId, secretKey)
        COSCredentials cred = new BasicCOSCredentials(ACCESSID, SECRETKEY);
        // 2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        // clientConfig中包含了设置region, https(默认http), 超时, 代理等set方法, 使用可参见源码或者接口文档FAQ中说明
        ClientConfig clientConfig = new ClientConfig(new Region(REGIONID));
        // 3 生成cos客户端
        COSClient cosClient = new COSClient(cred, clientConfig);
        // bucket的命名规则为{name}-{appid} ，此处填写的存储桶名称必须为此格式
        //String bucketName = BUCKETNAME;
        return cosClient;
    }
     */
    public  static COSClient getCosClient(String accessId,String secretKey,String regionId) {
        // 1 初始化用户身份信息(secretId, secretKey)
        COSCredentials cred = new BasicCOSCredentials(accessId, secretKey);
        // 2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        // clientConfig中包含了设置region, https(默认http), 超时, 代理等set方法, 使用可参见源码或者接口文档FAQ中说明
        ClientConfig clientConfig = new ClientConfig(new Region(regionId));
        // 3 生成cos客户端
        COSClient cosClient = new COSClient(cred, clientConfig);
        // bucket的命名规则为{name}-{appid} ，此处填写的存储桶名称必须为此格式
        //String bucketName = BUCKETNAME;
        return cosClient;
    }

    /**
     * 上传文件
     * @return
     * //绝对路径和相对路径都OK
     */
    public static  String uploadFile(String bucketName,String key, File file,COSClient cc) {
        //File localFile = new File("E:\\isTake.png");
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file);
        String etag = null;
        // 设置存储类型, 默认是标准(Standard), 低频(standard_ia),一般为标准的
        putObjectRequest.setStorageClass(StorageClass.Standard);

        try {
            PutObjectResult putObjectResult = cc.putObject(putObjectRequest);
            // putobjectResult会返回文件的etag
            etag = putObjectResult.getETag();
        } catch (CosServiceException e) {
            e.printStackTrace();
        } catch (CosClientException e) {
            e.printStackTrace();
        }
        // 关闭客户端
        cc.shutdown();
        return etag;
    }

    /**
     * 下载文件
     * @param bucketName
     * @param key
     * @return
     */
    public   String downLoadFile(File downFile, String key,COSClient cc) {
        //File downFile = new File("E:\\software\\1.jpg");
        GetObjectRequest getObjectRequest = new GetObjectRequest(BUCKETNAME, key);
        
        ObjectMetadata downObjectMeta = cc.getObject(getObjectRequest, downFile);
        cc.shutdown();
        String etag = downObjectMeta.getETag();
        return etag;
    }

    /**
     * 删除文件
     * @param bucketName
     * @param key
     */
    public   void deleteFile( String key,COSClient cc) {
        try {
            cc.deleteObject(BUCKETNAME, key);
        } catch (CosClientException e) {
            e.printStackTrace();
        } finally {
            cc.shutdown();
        }

    }

    /**
     * 创建桶
     * @param bucketName
     * @return
     * @throws CosClientException
     * @throws CosServiceException
     */
    public   Bucket createBucket(String bucketName,COSClient cc) throws CosClientException, CosServiceException {
        Bucket bucket = null;
        try {
            bucket = cc.createBucket(bucketName);
        } catch (CosClientException e) {
            e.printStackTrace();
        } finally {
        }
        return bucket;
    };

    /**
     * 删除桶
     * @param bucketName
     * @throws CosClientException
     * @throws CosServiceException
     */
    public void deleteBucket(String bucketName,COSClient cc) throws CosClientException, CosServiceException {
        try {
            cc.deleteBucket(bucketName);
        } catch (CosClientException e) {
            e.printStackTrace();
        } finally {
        }
    };

    /**
     * 判断桶是否存在
     * @param bucketName
     * @return
     * @throws CosClientException
     * @throws CosServiceException
     */
    public   boolean doesBucketExist(String bucketName,COSClient cc) throws CosClientException, CosServiceException {
        boolean bucketExistFlag = cc.doesBucketExist(bucketName);
        return bucketExistFlag;
    };

    /**
     * 查看桶文件
     * @param bucketName
     * @return
     * @throws CosClientException
     * @throws CosServiceException
     */
    public   ObjectListing listObjects(String bucketName,COSClient cc) throws CosClientException, CosServiceException {

        // 获取 bucket 下成员（设置 delimiter）
        ListObjectsRequest listObjectsRequest = new ListObjectsRequest();
        listObjectsRequest.setBucketName(bucketName);
        // 设置 list 的 prefix, 表示 list 出来的文件 key 都是以这个 prefix 开始
        listObjectsRequest.setPrefix("");
        // 设置 delimiter 为/, 即获取的是直接成员，不包含目录下的递归子成员
        listObjectsRequest.setDelimiter("/");
        // 设置 marker, (marker 由上一次 list 获取到, 或者第一次 list marker 为空)
        listObjectsRequest.setMarker("");
        // 设置最多 list 100 个成员,（如果不设置, 默认为 1000 个，最大允许一次 list 1000 个 key）
        listObjectsRequest.setMaxKeys(100);

        ObjectListing objectListing = cc.listObjects(listObjectsRequest);
        // 获取下次 list 的 marker
        String nextMarker = objectListing.getNextMarker();
        // 判断是否已经 list 完, 如果 list 结束, 则 isTruncated 为 false, 否则为 true
        boolean isTruncated = objectListing.isTruncated();
        List<COSObjectSummary> objectSummaries = objectListing.getObjectSummaries();
        for (COSObjectSummary cosObjectSummary : objectSummaries) {
            // get file path
            String key = cosObjectSummary.getKey();
            // get file length
            long fileSize = cosObjectSummary.getSize();
            // get file etag
            String eTag = cosObjectSummary.getETag();
            // get last modify time
            Date lastModified = cosObjectSummary.getLastModified();
            // get file save type
            String StorageClassStr = cosObjectSummary.getStorageClass();
        }
        return objectListing;
    }

    /**
     *查询一个 Bucket 所在的 Region。
     * @param bucketName
     * @return
     * @throws CosClientException
     * @throws CosServiceException
     */
    public   String getBucketLocation(String bucketName,COSClient cosClient) throws CosClientException , CosServiceException{
        // bucket 的命名规则为{name}-{appid} ，此处填写的存储桶名称必须为此格式
        String location = cosClient.getBucketLocation(bucketName);
        return location;
    }

    
    
    public static String uploadFile(String bucketName,String key, InputStream input,COSClient cc){
    	String etag = null;
    	ObjectMetadata objectMetadata = new ObjectMetadata();
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key,  input,null);
        // 设置存储类型, 默认是标准(Standard), 低频(standard_ia),一般为标准的
        putObjectRequest.setStorageClass(StorageClass.Standard);

        try {
            PutObjectResult putObjectResult = cc.putObject(putObjectRequest);
            // putobjectResult会返回文件的etag
            etag = putObjectResult.getETag();
        } catch (CosServiceException e) {
            e.printStackTrace();
        } catch (CosClientException e) {
            e.printStackTrace();
        }
        // 关闭客户端
        cc.shutdown();
        return etag;
    }
    /*
  public static  void main(String[] args) {
    	CosClientUtil  cosClientUtil = new CosClientUtil();
        File localFile = new File("E:\\1.png");
        String result = cosClientUtil.uploadFile("goods/076e3caed758a1c18c91a0e9cae3368f.png",localFile);
//        System.out.println("ETag:"+result);
//    	  File file = new File("goods/5405f9b57f5ada74a759c4c8dbccaf4d");
//    	  String result = cosClientUtil.downLoadFile(file, "5405f9b57f5ada74a759c4c8dbccaf4d");
//    	  System.out.println("ETag:"+result);
    	  cosClientUtil.deleteFile("goods/076e3caed758a1c18c91a0e9cae3368f.png");
//        createBucket("sunjunxian01-1251782781");
        //deleteBucket();
//        doesBucketExist("sunjunxian01-1251782781");
//        System.out.println(listObjects(BUCKETNAME));
//        System.out.println("BUCKETNAME的位置：" + cosClientUtil.getBucketLocation(cosClientUtil.BUCKETNAME));
        //File localFile = new File("D:\\files\\2019\\08\\16\\ba45c8f60456a672e003a875e469d0eb.jpg");
       // cosClientUtil.uploadFile("goods/ba45c8f60456a672e003a875e469d0eb",localFile);
    	//cosClientUtil.listObjects(cosClientUtil.BUCKETNAME+"-100005369859");
    	//cosClientUtil.listObjects(cosClientUtil.BUCKETNAME);
    	
    } 
	*/
}
